<template>
  <div class="medicine-management">
    <div class="page-header">
      <h1 class="page-title">药品管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
          新增药品
        </el-button>
        <el-button :icon="Upload" @click="showImportDialog = true">
          批量导入
        </el-button>
        <el-button :icon="Download" @click="exportMedicines">
          导出数据
        </el-button>
        <el-button
          :icon="Warning"
          @click="showAlertDialog = true"
          :badge="alertCount"
        >
          库存预警
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409eff">
              <el-icon><Medicine /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ medicineStats.total }}</div>
              <div class="stat-label">药品总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67c23a">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">
                ¥{{ medicineStats.totalValue.toFixed(2) }}
              </div>
              <div class="stat-label">库存总值</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card warning" @click="showLowStockDialog = true">
          <div class="stat-content">
            <div class="stat-icon" style="background: #e6a23c">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ medicineStats.lowStock }}</div>
              <div class="stat-label">库存不足</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card danger" @click="showExpiringDialog = true">
          <div class="stat-content">
            <div class="stat-icon" style="background: #f56c6c">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ medicineStats.expiring }}</div>
              <div class="stat-label">即将过期</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索药品名称、通用名或厂商"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filterCategory"
            placeholder="药品分类"
            clearable
            @change="handleFilter"
          >
            <el-option label="心血管用药" value="心血管用药" />
            <el-option label="抗感染药" value="抗感染药" />
            <el-option label="消化系统用药" value="消化系统用药" />
            <el-option label="呼吸系统用药" value="呼吸系统用药" />
            <el-option label="内分泌用药" value="内分泌用药" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filterType"
            placeholder="药品类型"
            clearable
            @change="handleFilter"
          >
            <el-option label="西药" value="西药" />
            <el-option label="中药" value="中药" />
            <el-option label="中成药" value="中成药" />
            <el-option label="生物制品" value="生物制品" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filterStatus"
            placeholder="状态"
            clearable
            @change="handleFilter"
          >
            <el-option label="在售" value="在售" />
            <el-option label="停售" value="停售" />
            <el-option label="缺货" value="缺货" />
            <el-option label="过期" value="过期" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <div class="filter-actions">
            <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
            <el-button
              :icon="Filter"
              @click="showAdvancedFilter = !showAdvancedFilter"
            >
              高级筛选
            </el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 高级筛选 -->
      <el-collapse-transition>
        <div v-show="showAdvancedFilter" class="advanced-filter">
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="价格区间">
                <el-input-number
                  v-model="priceRange[0]"
                  placeholder="最低价"
                  style="width: 45%"
                />
                <span style="margin: 0 8px">-</span>
                <el-input-number
                  v-model="priceRange[1]"
                  placeholder="最高价"
                  style="width: 45%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库存区间">
                <el-input-number
                  v-model="stockRange[0]"
                  placeholder="最低库存"
                  style="width: 45%"
                />
                <span style="margin: 0 8px">-</span>
                <el-input-number
                  v-model="stockRange[1]"
                  placeholder="最高库存"
                  style="width: 45%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="过期时间">
                <el-date-picker
                  v-model="expiryDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="filter-buttons">
                <el-button type="primary" @click="applyAdvancedFilter"
                  >应用筛选</el-button
                >
                <el-button @click="resetAdvancedFilter">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 药品列表 -->
    <el-card shadow="never">
      <el-table
        :data="paginatedMedicines"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="药品编号" width="100" />
        <el-table-column prop="name" label="药品名称" min-width="150">
          <template #default="{ row }">
            <div class="medicine-name">
              <el-button type="text" @click="handleViewDetail(row)">
                {{ row.name }}
              </el-button>
              <div class="generic-name">{{ row.genericName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)" size="small">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="specification" label="规格" width="100" />
        <el-table-column prop="price" label="售价" width="80">
          <template #default="{ row }"> ¥{{ row.price }} </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80">
          <template #default="{ row }">
            <span :class="getStockClass(row)">
              {{ row.stock }}{{ row.unit }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="manufacturer" label="生产厂商" width="120" />
        <el-table-column prop="expiryDate" label="有效期" width="110">
          <template #default="{ row }">
            <span :class="getExpiryClass(row.expiryDate)">
              {{ row.expiryDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleStock(row)">
              库存
            </el-button>
            <el-dropdown
              @command="(command: string) => handleMoreActions(command, row)"
            >
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="copy">复制药品</el-dropdown-item>
                  <el-dropdown-item command="barcode"
                    >条码打印</el-dropdown-item
                  >
                  <el-dropdown-item command="history"
                    >变动记录</el-dropdown-item
                  >
                  <el-dropdown-item command="disable" :disabled="row.stock > 0">
                    {{ row.status === "在售" ? "停售" : "启用" }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" :disabled="row.stock > 0">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredMedicines.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑药品对话框 (简化版) -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingMedicine ? '编辑药品' : '新增药品'"
      width="700px"
      @close="resetForm"
    >
      <div class="form-placeholder">
        <el-empty description="药品表单功能开发中" />
      </div>
    </el-dialog>

    <!-- 药品详情对话框 (简化版) -->
    <el-dialog v-model="showDetailDialog" title="药品详情" width="800px">
      <div v-if="currentMedicine" class="medicine-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="药品名称">{{
            currentMedicine.name
          }}</el-descriptions-item>
          <el-descriptions-item label="通用名">{{
            currentMedicine.genericName
          }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{
            currentMedicine.specification
          }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{
            currentMedicine.unit
          }}</el-descriptions-item>
          <el-descriptions-item label="售价"
            >¥{{ currentMedicine.price }}</el-descriptions-item
          >
          <el-descriptions-item label="库存"
            >{{ currentMedicine.stock
            }}{{ currentMedicine.unit }}</el-descriptions-item
          >
          <el-descriptions-item label="生产厂商">{{
            currentMedicine.manufacturer
          }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{
            currentMedicine.category
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 库存操作对话框 (简化版) -->
    <el-dialog v-model="showStockDialog" title="库存操作" width="500px">
      <div class="stock-placeholder">
        <el-empty description="库存操作功能开发中" />
      </div>
    </el-dialog>

    <!-- 库存预警对话框 -->
    <el-dialog v-model="showAlertDialog" title="库存预警" width="800px">
      <el-tabs>
        <el-tab-pane
          label="库存不足"
          :label="`库存不足(${lowStockMedicines.length})`"
        >
          <el-table :data="lowStockMedicines" max-height="400">
            <el-table-column prop="name" label="药品名称" />
            <el-table-column prop="stock" label="当前库存">
              <template #default="{ row }">
                {{ row.stock }}{{ row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="minStock" label="最低库存">
              <template #default="{ row }">
                {{ row.minStock }}{{ row.unit }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="handleQuickRestock(row)"
                >
                  快速入库
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          label="即将过期"
          :label="`即将过期(${expiringMedicines.length})`"
        >
          <el-table :data="expiringMedicines" max-height="400">
            <el-table-column prop="name" label="药品名称" />
            <el-table-column prop="batchNumber" label="批号" />
            <el-table-column prop="expiryDate" label="过期日期" />
            <el-table-column prop="stock" label="库存">
              <template #default="{ row }">
                {{ row.stock }}{{ row.unit }}
              </template>
            </el-table-column>
            <el-table-column label="剩余天数">
              <template #default="{ row }">
                {{ getRemainingDays(row.expiryDate) }}天
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog v-model="showImportDialog" title="批量导入药品" width="600px">
      <div class="import-content">
        <el-alert
          title="导入说明"
          description="请下载模板文件，填写药品信息后上传。支持Excel格式(.xlsx)。"
          type="info"
          show-icon
          :closable="false"
        />
        <div class="import-actions">
          <el-button @click="downloadTemplate">下载模板</el-button>
          <el-upload
            class="upload-demo"
            drag
            :on-change="handleFileChange"
            :auto-upload="false"
            accept=".xlsx"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button type="primary" @click="handleImport" :loading="importing">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Upload,
  Download,
  Warning,
  Search,
  Refresh,
  Filter,
  ArrowDown,
  Money,
  Clock,
  UploadFilled,
} from "@element-plus/icons-vue";
import { useMedicineStore } from "@/stores/modules/medicine";

// 这些组件暂时注释，使用内联对话框
// import MedicineFormDialog from './components/MedicineFormDialog.vue'
// import MedicineDetailDialog from './components/MedicineDetailDialog.vue'
// import StockOperationDialog from './components/StockOperationDialog.vue'

const medicineStore = useMedicineStore();

// 响应式数据
const searchQuery = ref("");
const filterCategory = ref("");
const filterType = ref("");
const filterStatus = ref("");
const showAdvancedFilter = ref(false);
const priceRange = ref<[number, number]>([0, 1000]);
const stockRange = ref<[number, number]>([0, 10000]);
const expiryDateRange = ref<[Date, Date] | null>(null);

const currentPage = ref(1);
const pageSize = ref(20);
const showAddDialog = ref(false);
const showDetailDialog = ref(false);
const showStockDialog = ref(false);
const showAlertDialog = ref(false);
const showImportDialog = ref(false);

const editingMedicine = ref<Medicine | null>(null);
const stockMedicine = ref<Medicine | null>(null);
const selectedMedicines = ref<Medicine[]>([]);
const loading = ref(false);
const importing = ref(false);

// 计算属性
const filteredMedicines = computed(() => {
  let result = medicineStore.medicines;

  if (searchQuery.value) {
    result = medicineStore.searchMedicines(searchQuery.value);
  }

  if (filterCategory.value) {
    result = result.filter((m) => m.category === filterCategory.value);
  }

  if (filterType.value) {
    result = result.filter((m) => m.type === filterType.value);
  }

  if (filterStatus.value) {
    result = result.filter((m) => m.status === filterStatus.value);
  }

  return result;
});

const paginatedMedicines = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredMedicines.value.slice(start, end);
});

const currentMedicine = computed(() => medicineStore.currentMedicine);
const medicineStats = computed(() => medicineStore.getMedicineStats());
const lowStockMedicines = computed(() => medicineStore.getLowStockMedicines());
const expiringMedicines = computed(() => medicineStore.getExpiringMedicines());

const alertCount = computed(() => {
  return lowStockMedicines.value.length + expiringMedicines.value.length;
});

// 方法
const handleSearch = () => {
  currentPage.value = 1;
};

const handleFilter = () => {
  currentPage.value = 1;
};

const handleRefresh = () => {
  medicineStore.getMedicines();
};

const applyAdvancedFilter = () => {
  // 应用高级筛选逻辑
  handleFilter();
};

const resetAdvancedFilter = () => {
  priceRange.value = [0, 1000];
  stockRange.value = [0, 10000];
  expiryDateRange.value = null;
  handleFilter();
};

const handleSelectionChange = (selection: Medicine[]) => {
  selectedMedicines.value = selection;
};

const handleRowClick = (row: Medicine) => {
  medicineStore.currentMedicine = row;
};

const handleViewDetail = (medicine: Medicine) => {
  medicineStore.currentMedicine = medicine;
  showDetailDialog.value = true;
};

const handleEdit = (medicine: Medicine) => {
  editingMedicine.value = medicine;
  showAddDialog.value = true;
};

const handleStock = (medicine: Medicine) => {
  stockMedicine.value = medicine;
  showStockDialog.value = true;
};

const handleMoreActions = async (command: string, medicine: Medicine) => {
  if (command === "copy") {
    editingMedicine.value = {
      ...medicine,
      id: "",
      name: `${medicine.name}(副本)`,
    };
    showAddDialog.value = true;
  } else if (command === "delete") {
    try {
      await ElMessageBox.confirm(
        `确定要删除药品"${medicine.name}"吗？`,
        "确认删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      );

      await medicineStore.deleteMedicine(medicine.id);
      ElMessage.success("删除成功");
    } catch (error) {
      if (error !== "cancel") {
        ElMessage.error("删除失败");
      }
    }
  } else if (command === "disable") {
    const newStatus = medicine.status === "在售" ? "停售" : "在售";
    try {
      await medicineStore.updateMedicine(medicine.id, { status: newStatus });
      ElMessage.success(`${newStatus === "在售" ? "启用" : "停售"}成功`);
    } catch (error) {
      ElMessage.error("操作失败");
    }
  }
};

const handleSave = () => {
  medicineStore.getMedicines();
  resetForm();
};

const handleStockSuccess = () => {
  medicineStore.getMedicines();
};

const resetForm = () => {
  editingMedicine.value = null;
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

const handleQuickRestock = (medicine: Medicine) => {
  stockMedicine.value = medicine;
  showStockDialog.value = true;
  showAlertDialog.value = false;
};

const exportMedicines = () => {
  ElMessage.info("导出功能待开发");
};

const downloadTemplate = () => {
  ElMessage.info("模板下载功能待开发");
};

const handleFileChange = (file: any) => {
  // 处理文件上传
};

const handleImport = () => {
  ElMessage.info("导入功能待开发");
};

const getRemainingDays = (expiryDate: string) => {
  const today = new Date();
  const expiry = new Date(expiryDate);
  const diffTime = expiry.getTime() - today.getTime();
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
};

// 样式辅助方法
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    西药: "primary",
    中药: "success",
    中成药: "warning",
    生物制品: "danger",
  };
  return colorMap[type] || "info";
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    在售: "success",
    停售: "info",
    缺货: "warning",
    过期: "danger",
  };
  return colorMap[status] || "info";
};

const getStockClass = (medicine: Medicine) => {
  if (medicine.stock <= 0) return "stock-empty";
  if (medicine.stock <= medicine.minStock) return "stock-low";
  return "stock-normal";
};

const getExpiryClass = (expiryDate: string) => {
  const remainingDays = getRemainingDays(expiryDate);
  if (remainingDays <= 0) return "expired";
  if (remainingDays <= 30) return "expiring-soon";
  return "normal";
};

onMounted(() => {
  medicineStore.getMedicines();
});
</script>

<style lang="scss" scoped>
.medicine-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.stats-cards {
  margin-bottom: 20px;

  .stat-card {
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    &.warning:hover {
      border-color: #e6a23c;
    }

    &.danger:hover {
      border-color: #f56c6c;
    }

    .stat-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 24px;
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 700;
          color: #303133;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;

  .filter-actions {
    display: flex;
    gap: 8px;
  }

  .advanced-filter {
    margin-top: 16px;

    .filter-buttons {
      text-align: right;
    }
  }
}

.medicine-name {
  .generic-name {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }
}

.stock-empty {
  color: #f56c6c;
  font-weight: bold;
}

.stock-low {
  color: #e6a23c;
  font-weight: bold;
}

.stock-normal {
  color: #67c23a;
}

.expired {
  color: #f56c6c;
  font-weight: bold;
}

.expiring-soon {
  color: #e6a23c;
  font-weight: bold;
}

.normal {
  color: #303133;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.import-content {
  .import-actions {
    margin-top: 20px;
    display: flex;
    gap: 20px;
    align-items: center;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .stats-cards {
    :deep(.el-col) {
      margin-bottom: 16px;
    }
  }

  .search-card {
    :deep(.el-row) {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
